home *** CD-ROM | disk | FTP | other *** search
- Path: utopia.hacktic.nl!not-for-mail
- From: Mike Tavares <MIKET@cdynamics.com>
- Newsgroups: comp.lang.c++
- Subject: String operator+ and memory leakage.
- Date: 18 Apr 1996 15:23:36 +0200
- Organization: Hack-Tic International, Inc.
- Sender: remailer@utopia.hacktic.nl
- Message-ID: <4l5foo$fen@utopia.hacktic.nl>
- NNTP-Posting-Host: utopia.hacktic.nl
- Content-Type: text/plain; charset=US-ASCII
- Content-Transfer-Encoding: 7bit
- Comment: This message was forwarded by an automated remailing service.
- Comment: No attempt was made to verify the sender's identity.
- Comment: Please report misuse to <postmaster@utopia.hacktic.nl>
-
- I have an implementation (not mine) of the String class that is leaking
- memory
- during the + operator code. The code follows:
-
- class String
- {
- public:
-
- // Constructors/destructors
- String();
- String( char* new_string);
- String( String& new_string);
-
- ~String()
- {
- delete character_array;
- }
-
- String& operator+( String& a_string );
- String& operator=( String& a_string );
- operator char* () { return character_array; }
-
- private:
-
- char* character_array;
- int string_length;
- };
-
- String&
- String::operator+( String& a_string )
- {
- int total_size = string_length + strlen( a_string ) + 1;
- char* temp_array = new char[total_size];
- char* char_array = a_string;
-
- strcpy( temp_array, character_array );
- strcat( temp_array, char_array );
-
- String* new_string = new String( temp_array );
- delete [] temp_array;
- return *new_string;
- }
-
- String&
- String::operator=( String& a_string )
- {
- char* new_char_array = a_string;
- delete [] character_array;
- character_array = new char[strlen( new_char_array ) + 1];
- strcpy( character_array, new_char_array );
- string_length = strlen( character_array );
- return *this;
- }
-
- My usage is:
-
- destString = string1 + string2 + string3...;
-
-
- The problem is, when new_string is created and returned through a
- reference, no one ever deletes it.
-
- If I change new_string to be an automatic variable I get an error from
- the compiler about trying to pass a reference to a item that is out of
- scope.
-
- If I change the method to work in this I mutate one of my addends. There
- has to be a way of implementing this without memory leakage! HELP!
-
- TIA
-
- =MikeT
-
- ---------------------------------------------------------------------
- | Mike Tavares | miket@cdynamics.com | |
- | Software Engineer | | If you're not lead |
- | ----- | ----- | dog the view never |
- | Computer Dynamics | (803) 627-8800 | changes. |
- | 7640 Pelham Rd | EXT - 232 | |
- | Greenville, SC 29615 | Fax. (803) 675-0106 | Email for PGP key |
- |==================================================================== |
- | Computer Dynamics - The Flat Panel Experts |
- ---------------------------------------------------------------------
-
-
-